package demoApiOfKboot.action;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
 
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;


/**
 *文件上传的demo，包含springboot 自带页面
 * @author caix
 *
 */
@Controller
public class UploadFileDemoAction {
   
    //访问路径为：http://127.0.0.1:8080/file
    @RequestMapping("/displayUpload")
    public String file(){
       return"/uploadfilepage";
    }
   
    /**
     * 文件上传具体实现方法;
     * @param file
     * @return
     */
    @RequestMapping("/upload")
    @ResponseBody
    public String handleFileUpload(@RequestParam("file")MultipartFile file){
       if(!file.isEmpty()){
           try {
              BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(new File("d://"+file.getOriginalFilename())));
              out.write(file.getBytes());
              out.flush();
              out.close();
           } catch (FileNotFoundException e) {
              e.printStackTrace();
              return"上传失败,"+e.getMessage();
           } catch (IOException e) {
              e.printStackTrace();
              return"上传失败,"+e.getMessage();
           }
           return"上传成功";
       }else{
           return"上传失败，因为文件是空的.";
       }
    }
}
